package com.drd.dt.back.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.drd.dt.util.MD5Utils;
import com.drd.dt.util.ResultUtil;
import com.drd.dt.back.dao.LoginMapper;
import com.drd.dt.back.service.ILoginService;
import com.drd.dt.common.SuccessResultEnum;
import com.drd.dt.common.tips.Tip;
import com.drd.dt.exception.BizExceptionEnum;
import com.drd.dt.exception.BussinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * Created by 86514 on 2019/4/10.
 */
@Transactional
@Service
public class LoginServiceImpl implements ILoginService {

    @Autowired
    private LoginMapper loginMapper;

    @Override
    public Tip login(Map<Object, Object> map) throws Exception{
        String userName = map.get("username").toString();
        String userPwd = map.get("pwd").toString();
        if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(userPwd)){
            throw new BussinessException(BizExceptionEnum.USER_USERNAME_EMPTY);
        }
        Map admin = loginMapper.getAdminByUserName(userName);
        if (null == admin){
            throw new BussinessException(BizExceptionEnum.OT_USER_ERROR);
        }
        String password = admin.get("password").toString();
        String type = admin.get("type").toString();
        String md5Pwd = MD5Utils.MD5Encode(userPwd, "UTF-8");
        if (password.equals(md5Pwd)){
            JSONObject json = new JSONObject();
            json.put("userName",userName);
            json.put("password",userPwd);
            json.put("type",type);
            return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), json);
        }else {
            throw new BussinessException(BizExceptionEnum.USER_LOGIN_PWD_ERROR);
        }
    }
}
